<template>
  <!-- 抽屉 -->
  <el-drawer
    v-if="showDrawer"
    v-model="drawer"
    :title="list.id == 0 ? '添加用户' : '修改用户'"
    :direction="direction"
    :before-close="handleClose"
  >
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :model="list"
      label-position="left"
      label-width="auto"
    >
      <el-form-item label="用户名称" prop="username">
        <el-input type="text" v-model="list.username" />
      </el-form-item>
      <el-form-item label="角色名称" prop="name">
        <!-- 下拉选择角色名称 -->
        <el-select
          v-model="list.name"
          placeholder="请选择角色名称"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in selectTheList"
            :key="item.roleName"
            :label="item.roleName"
            :value="item.roleName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!list.id">
        <el-input type="text" v-model="list.password" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input type="text" v-model="list.phone" />
      </el-form-item>
      <el-form-item label="头像" prop="imgUrl">
        <!-- 头像上传 -->
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          list-type="text"
          :action="base + 'user/upload'"
          :limit="limit"
          :on-exceed="handleExceed"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-image
            style="width: 178px; height: 178px"
            v-if="list.imgUrl"
            :src="base + list.imgUrl"
            class="avatar"
            fit="cover"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-form-item class="btn">
      <el-button v-if="list.id === 0" type="primary" @click="addUser(ruleFormRef)">添加</el-button>
      <el-button v-else type="primary" @click="updateUser(ruleFormRef)">修改</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, watch } from 'vue'
import { updateUserApi, addUserApi } from '@/apis/user'
import type { DrawerProps, FormInstance, FormRules } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
const showDrawer = ref(false)
// 抽屉变量
const drawer = ref(false)
let emits = defineEmits(['get-user'])

// 接收角色名称选择框数据
defineProps({
  selectTheList: {
    type: Object
  }
})
// 接收父组件传递的id给服务器返回的数据
const list = ref({
  id: 0,
  username: '',
  name: '',
  password: '',
  phone: '',
  imgUrl: ''
})
defineExpose({ drawer, list, showDrawer })
// 监听drawer.value来控制这个组件的v-if
watch(
  () => drawer.value,
  (newVal) => {
    if (newVal) {
      showDrawer.value = true
    } else {
      setTimeout(() => {
        showDrawer.value = false
      }, 100)
    }
  }
)
const ruleFormRef = ref<FormInstance>()
// 用户名称验证
const validateusername = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名称！'))
  } else {
    callback()
  }
}
// 角色名称验证
const validatename = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入角色名称！'))
  } else {
    callback()
  }
}
// 电话称验证
const validatephone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入电话！'))
  } else {
    callback()
  }
}
// 头像称证
const validateimgUrl = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请上传头像！'))
  } else {
    callback()
  }
}
// 密码验证
const validatepassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码！'))
  } else {
    callback()
  }
}
// 表单验证规则
const rules = reactive<FormRules<typeof list>>({
  username: [{ validator: validateusername, trigger: 'blur' }],
  name: [{ validator: validatename, trigger: 'blur' }],
  phone: [{ validator: validatephone, trigger: 'blur' }],
  password: [{ validator: validatepassword, trigger: 'blur' }],
  imgUrl: [{ validator: validateimgUrl, trigger: 'blur' }]
})
// 控制抽屉打开方向
const direction = ref<DrawerProps['direction']>('rtl')
// 关闭抽屉前的回调
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('是否关闭这个?')
    .then(() => {
      drawer.value = false
      list.value = {
        id: 0,
        username: '',
        name: '',
        password: '',
        phone: '',
        imgUrl: '' // 定义上传图片路径
      }

      done()
    })
    .catch(() => {
      // catch error
    })
}
const base = import.meta.env.VITE_APP_BASE_API
// 上传功能
// 上传文件的数量
const limit = ref(5)
// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  let { filename, success } = response
  if (success) {
    ElMessage({
      message: '头像上传成功',
      type: 'success'
    })
    list.value.imgUrl = filename
  }
}
// 上传之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let imgType = ['image/jpeg', 'image/jpg', 'image/png']
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error('上传的格式需要jpeg,jpg,png!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('照片大小不能超过1MB!')
    return false
  }
  return true
}
// 超过上传图片限制提示事件
const handleExceed = (files: any, uploadFiles: any) => {
  ElMessageBox.alert('只能上传五个文件，如果有需要请刷新页面', '温馨提示', {
    confirmButtonText: '确认'
  })
}
// const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
//   //执行该方法时自动移除el-upload上显示的图片，所以方法体内只需要移除已上传的图片即可
//   const index = fileImg.value.findIndex((item) => (item = file.url))
//   fileImg.value.splice(index, 1) //移除已上传的图片
// }
const userStore = useUserStore()
// 更新用户信息
const updateUser = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await updateUserApi({
        id: list.value.id,
        name: list.value.name,
        phone: list.value.phone,
        username: list.value.username,
        imgUrl: list.value.imgUrl
      })
      drawer.value = false
      if (list.value.username === userStore.user!.username) {
        userStore.user!.imgUrl = list.value.imgUrl
        userStore.user!.name = list.value.name
        userStore.user!.phone = list.value.phone
        userStore.user!.username = list.value.username
      }
      list.value = {
        id: 0,
        username: '',
        name: '',
        password: '',
        phone: '',
        imgUrl: ''
      }
      emits('get-user')
      ElMessage({
        type: 'success',
        message: '修改成功。'
      })
    } else {
      ElMessage({
        type: 'error',
        message: '表单数据输入存在错误，修改失败。'
      })
      return false
    }
  })
}
// 添加用户
const addUser = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await addUserApi(list.value)
      drawer.value = false
      emits('get-user')
      ElMessage({
        type: 'success',
        message: '添加成功。'
      })
    } else {
      ElMessage({
        type: 'error',
        message: '表单数据输入存在错误，添加失败。'
      })
      return false
    }
  })
}
// 重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.btn {
  margin-left: 68px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
